import jwt, datetime
import config
from services.utils import json_result
from werkzeug.exceptions import Unauthorized

class JwtServer():
    def generate_token(data):
        payload = {
            'exp': datetime.datetime.utcnow() + datetime.timedelta(config.EXPIRE),  # Token有效期设置为1天
            'iat': datetime.datetime.utcnow(),
            'data': data
        }
        token = jwt.encode(payload, config.SECRET_KEY, algorithm = 'HS256')

        return token
    
    def get_payload(token):
        try:
            verified_payload = jwt.decode(jwt=token, key=config.SECRET_KEY, verify=True, algorithms=["HS256"])
            return verified_payload
        except jwt.ExpiredSignatureError:
            raise Unauthorized(description = 'token已过期')
        except jwt.DecodeError:
            raise Unauthorized(description = 'token认证失败')
        except jwt.InvalidTokenError:
            raise Unauthorized(description = '非法的token')